package com.ews.onlineexchange.service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import javax.persistence.EntityManager;

import com.ews.onlineexchange.model.*;
import com.ews.onlineexchange.model.ShortMessage;
import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.ews.onlineexchange.service.qualifier.SendEmailEvent;
import com.ews.onlineexchange.util.SmsSender;
import com.ews.onlineexchange.util.SmsTemplateMapUtils;

@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class SmsService {
	//private Map<String,String> params = new HashMap<String, String>();
	private JSONObject params = new JSONObject();
	static DateFormat df;
	static {
		df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	}
	
	
	/**
	 * 中介被黑名单
	 * 您在东营市网上中介超市的帐号因被东营市行政审批服务局列为信用黑名单成员，您的注册帐号将被暂时停用。具体信息请联系东营市东营区发改局。
	 * 
	 * ${sb}，您好：您在东营市网上中介超市的帐号因被东营市行政审批服务局列为信用黑名单成员，您的注册帐号将被暂时停用。具体信息请联系东营市东营区发改局。
	 */
	public void addSupplierBlackList(ServiceSupplier supplier) {
		StringBuilder sb = new StringBuilder();
		sb	.append((supplier.getCnname()))
			.append("，您好:")	
			.append("您在东营市网上中介超市的帐号因被东营市行政审批服务局列为信用黑名单成员，您的注册帐号将被暂时停用。具体信息请联系东营市行政审批服务局。");
		params = new JSONObject();
		params.put("sb", getParam(supplier.getCnname()));
		String result = SmsSender.sendSms( getDestNumber(supplier),SmsTemplateMapUtils.BLACKLIST_TEMPLATE,params.toString());
		ShortMessage message = new ShortMessage(sb.toString(),getDestNumber(supplier), SmsTemplateMapUtils.BLACKLIST_TEMPLATE, params.toString());
		saveFeedbackMsg(result, message);
		StringBuilder title = new StringBuilder();
		title.append("被列入黑名单通知");
		//消息通知
		notificationService.sendNotification(title.toString(), null, sb.toString(), supplier);
		
	}
	
	/**
	 * 中介基本信息临近过期提醒
	 * 您的注册信息已经临近过期，为避免您的正常业务受到影响，请尽快完善您的注册信息并前往【黄河三角洲第三方服务基地建设领导小组办公室】参加复审。
	 * 
	 * ${sb}，您好：您的注册信息已经临近过期，为避免您的正常业务受到影响，请尽快完善您的注册信息并前往黄河三角洲第三方服务基地建设领导小组办公室参加复审。
	 */
	public void addSupplierExpire(ServiceSupplier supplier) {
		StringBuilder sb = new StringBuilder();
		sb	.append((supplier.getCnname()))
			.append("，您好:")
			.append("您的注册信息已临近过期，为避免您的正常业务受到影响，请尽快完善您的注册信息。");
		params = new JSONObject();
		params.put("sb", getParam(supplier.getCnname()));
		String result = SmsSender.sendSms( getDestNumber(supplier),SmsTemplateMapUtils.BASIC_INFOMATION_NEAR_EXPIRED_TEMPLATE,params.toString());
		ShortMessage message = new ShortMessage(sb.toString(),getDestNumber(supplier), SmsTemplateMapUtils.BASIC_INFOMATION_NEAR_EXPIRED_TEMPLATE, params.toString());
		saveFeedbackMsg(result, message);
		StringBuilder title = new StringBuilder();
		title.append("中介基本信息临近过期通知");
		//消息通知
		notificationService.sendNotification(title.toString(), null, sb.toString(), supplier);
	}
	
	public void determinedRecordFailNotification(ServiceSupplier supplier) {
		StringBuilder sb = new StringBuilder();
		sb
		.append("关于对")	
		.append((supplier.getCnname()))
			.append("的整改期限已到，系统已自动撤销！");
		params = new JSONObject();
		params.put("supplierName", getParam(supplier.getCnname()));
		String result = SmsSender.sendSms( getDestNumber(supplier),SmsTemplateMapUtils.DETERMINED_RECORD_FAIL_NOTIFICATION_TEMPLATE,params.toString());
		ShortMessage message = new ShortMessage(sb.toString(),getDestNumber(supplier), SmsTemplateMapUtils.DETERMINED_RECORD_FAIL_NOTIFICATION_TEMPLATE.toString());
		saveFeedbackMsg(result, message);
		StringBuilder title = new StringBuilder();
		title.append("整改期限已到通知");
		//消息通知
		notificationService.sendNotification(title.toString(), null, sb.toString(), supplier);
	}
	
	
	public void determinedRecordSuccessNotification(ServiceSupplier supplier) {
		StringBuilder sb = new StringBuilder();
		sb	.append((supplier.getCnname()))
		.append("，您好:")
		.append("您已被加入到整改名单中，在此期间，将不能参与项目选取！");
		params = new JSONObject();
		params.put("cname", getParam(supplier.getCnname()));
		String result = SmsSender.sendSms( getDestNumber(supplier),SmsTemplateMapUtils.DETERMINED_RECORD_SUCCESS_NOTIFICATION_TEMPLATE,params.toString());
		ShortMessage message = new ShortMessage(sb.toString(),getDestNumber(supplier), SmsTemplateMapUtils.DETERMINED_RECORD_SUCCESS_NOTIFICATION_TEMPLATE.toString());
		saveFeedbackMsg(result, message);
		StringBuilder title = new StringBuilder();
		title.append("被列入整改名单通知");
		//消息通知
		notificationService.sendNotification(title.toString(), null, sb.toString(), supplier);
	}
	
	/**
	 * 中介资质临近过期提醒
	 * 您的注册证书【证书大类名称】临近过期，为避免您的正常业务受到影响。请尽快完善证书信息并前往【这里是行业部门？】参加复审。
	 * 
	 * ${sb}，您好：您的注册证书${qualificationClass}临近过期，为避免您的正常业务受到影响。请尽快完善证书信息并前往${auditDepartment}参加复审。
	 */
	public void addCertExpire(QualificationCert cert) {
		StringBuilder sb = new StringBuilder();
		sb	.append((cert.getServiceSupplier().getCnname()))
			.append("，您好:")
			.append("您的注册证书【")
			.append(cert.getQualificationClass().getName())
			.append("】临近过期，为避免您的正常业务受到影响，请登录系统及时更新证书信息。");

		params = new JSONObject();
		params.put("sb", getParam(cert.getServiceSupplier().getCnname()));
		params.put("qualificationClass", getParam(cert.getQualificationClass().getName()));
		String result = SmsSender.sendSms( getDestNumber(cert.getServiceSupplier()),SmsTemplateMapUtils.CERT_NEAR_EXPIRED_TEMPLATE,params.toString());
		ShortMessage message = new ShortMessage(sb.toString(),getDestNumber(cert.getServiceSupplier()), SmsTemplateMapUtils.CERT_NEAR_EXPIRED_TEMPLATE,params.toString());
		saveFeedbackMsg(result, message);
		StringBuilder title = new StringBuilder();
		title.append("资质临近过期通知");
		//消息通知
		notificationService.sendNotification(title.toString(), null, sb.toString(), cert.getServiceSupplier());
	}
	
	public void cancelAppliedByBuyer(Trade trade) {
		Bulletin bulletin = trade.getBulletin();
		StringBuilder content = new StringBuilder();
		 ServiceSupplier supplier = trade.getSupplier();
		content.append("\n")
						.append(supplier.getCnname())
						.append("，您好:\n")
						.append("您在东营市网上中介超市报名参与的【")
						.append(bulletin.getProjectName())
						.append("】,由于'")
						.append(trade.getCancelReason())
						.append("'原因，被采购方取消报名,请修改后重新报名！");

		params = new JSONObject();
		params.put("cnname", getParam(supplier.getCnname()));
		params.put("projectName", getParam(bulletin.getProjectName()));
		params.put("cancelReason", getParam(trade.getCancelReason()));
		String result = SmsSender.sendSms( getDestNumber(supplier),SmsTemplateMapUtils.CANCEL_APPLIED_BY_BUYER_NOTIFICATION_TEMPLATE,params.toString());
		ShortMessage message = new ShortMessage(content.toString(),getDestNumber(supplier), SmsTemplateMapUtils.CANCEL_APPLIED_BY_BUYER_NOTIFICATION_TEMPLATE,params.toString());
		saveFeedbackMsg(result, message);
		StringBuilder title = new StringBuilder();
		title.append("【")
		.append(bulletin.getProjectName())
		.append("】")
		.append("被取消报名通知");
		//消息通知
		notificationService.sendNotification(title.toString(), null, content.toString(), supplier);
	}
	
	/**
	 * 公告被驳回
	 * 您在东营市网上中介超市发布的【项目名称】公告，已被管理员驳回，请您尽快检查并完善公告信息。
	 * ${sb}，您好：您在东营市网上中介超市发布的${projectName}公告，已被管理员驳回，请您尽快检查并完善公告信息。
	 */
	public void addBulletinReject(Bulletin bulletin) {
		StringBuilder sb = new StringBuilder();
		sb	.append((bulletin.getBuyer().getCnname()))
			.append("，您好:")
			.append("您发布的【")
			.append(bulletin.getProjectName())
			.append("】公告,已被管理员驳回，请您尽快检查并完善公告信息。");
		params = new JSONObject();
		params.put("sb", getParam(bulletin.getBuyer().getCnname()));
		params.put("projectName", getParam(bulletin.getProjectName()));
		String result = SmsSender.sendSms( getDestNumber(bulletin.getBuyer()),SmsTemplateMapUtils.AUDIT_REJECT_TEMPLATE,params.toString());
		ShortMessage message = new ShortMessage(sb.toString(),getDestNumber(bulletin.getBuyer()), SmsTemplateMapUtils.AUDIT_REJECT_TEMPLATE,params.toString());
		saveFeedbackMsg(result, message);
		StringBuilder title = new StringBuilder();
		title.append("【")
		.append(bulletin.getProjectName())
		.append("】")
		.append("被驳回通知");
		//消息通知
		notificationService.sendNotification(title.toString(), null, sb.toString(), bulletin.getBuyer());
	}
	
	/**
	 * 向中介公司发送中标通知
	 * 您在东营市网上中介超市报名参与的【项目名称】】，已经选取完成，恭喜您中选。
	 * 
	 * ${sb}，您好：您在东营市网上中介超市报名参与的${projectName}，已经选取完成，恭喜您中选。
	 */
	public void addWinMessageToSupplier(Bulletin bulletin) {
		StringBuilder sb = new StringBuilder();
		sb	.append((bulletin.getSuccessTrade().getSupplier().getCnname()))
			.append("，您好:")
			.append("您报名参与的【")
			.append(bulletin.getProjectName())
			.append("】，已经选取完成，恭喜您中选。");
		params = new JSONObject();
		params.put("sb", getParam(bulletin.getSuccessTrade().getSupplier().getCnname()));
		params.put("projectName", getParam(bulletin.getProjectName()));
		String result = SmsSender.sendSms( getDestNumber(bulletin.getSuccessTrade().getSupplier()),SmsTemplateMapUtils.RESULT_NOTIFICATION_SUPPLIER_TEMPLATE,params.toString());
		ShortMessage message = new ShortMessage(sb.toString(),getDestNumber(bulletin.getSuccessTrade().getSupplier()), SmsTemplateMapUtils.RESULT_NOTIFICATION_SUPPLIER_TEMPLATE,params.toString());
		saveFeedbackMsg(result, message);
		StringBuilder title = new StringBuilder();
		title.append("【")
		.append(bulletin.getProjectName())
		.append("】")
		.append("中选通知");
		//消息通知
		notificationService.sendNotification(title.toString(), null, sb.toString(), bulletin.getBuyer());
	}
	
	/**
	 * 择优选取 向中介公司发送候选通知
	 * 
	 * ${sb}，您好：您参与的${projectName}，项目编号${serialNumber}已经选取完成，恭喜您成为候选中介之一，请电话咨询相关事宜0546-8966546。
	 * 
	 */
	public void addCandidateMessageToSupplier(String projectName,String serialNumber,ServiceSupplier supplier) {
		StringBuilder sb = new StringBuilder();
		sb	.append(supplier.getCnname())
			.append("，您好:")
			.append("您参与的【")
			.append(projectName)
			.append("】，项目编号【")
			.append(serialNumber)
			.append("】已经选取完成，恭喜您成为候选中介之一，请联系所属地区行政审批部门咨询相关事宜。");
		params = new JSONObject();
		params.put("sb", getParam(supplier.getCnname()));
		params.put("projectName", getParam(projectName));
		params.put("serialNumber", getParam(serialNumber));
		String result = SmsSender.sendSms( getDestNumber(supplier),SmsTemplateMapUtils.BEST_CHOOSE_RESULT_NOTIFICATION_TO_SUPPLIER_TEMPLATE,params.toString());
		ShortMessage message = new ShortMessage(sb.toString(),getDestNumber(supplier), SmsTemplateMapUtils.BEST_CHOOSE_RESULT_NOTIFICATION_TO_SUPPLIER_TEMPLATE,params.toString());
		saveFeedbackMsg(result, message);
		StringBuilder title = new StringBuilder();
		title.append("【")
		.append(projectName)
		.append("】，中选通知");
		//消息通知
		notificationService.sendNotification(title.toString(), null, sb.toString(), supplier);
	}
	@Inject
	NotificationService notificationService;
	public void notificationSupplierCertAuditFail(QualificationCert cert) {
		StringBuilder sb = new StringBuilder();
		ServiceSupplier supplier = cert.getServiceSupplier();
		sb	.append(supplier.getCnname())
		.append("||")
		.append("您的资质证书【")
		.append(cert.getQualificationClass().getName())
		.append("】被驳回，请及时修改，并重新提交审核!");
		params = new JSONObject();
		params.put("cnname", cert.getServiceSupplier().getCnname());
		params.put("className", cert.getQualificationClass().getName());
		String result = SmsSender.sendSms( getDestNumber(supplier),SmsTemplateMapUtils.NOTIFICATION_SERVICESUPPLIER_CERT_AUDIT_FAIL_TEMPLATE,params.toString());
		ShortMessage message = new ShortMessage(sb.toString(),getDestNumber(supplier), SmsTemplateMapUtils.NOTIFICATION_SERVICESUPPLIER_CERT_AUDIT_FAIL_TEMPLATE,params.toString());
		saveFeedbackMsg(result, message);
		
		StringBuilder title = new StringBuilder();
		title.append("【")
		.append(cert.getQualificationClass().getName())
		.append("】驳回通知");
		//消息通知
		notificationService.sendNotification(title.toString(), null, sb.toString(), supplier);
	}
	
	/**
	 * 择优选取 向采购方公司发送选取完成通知
	 * 
	 * ${sb}，您好：您发布的${projectName}已经选取完成，候选中介如下：${bestTradeSupplierCnname}.
	 */
	public void addCandidateMessageToBuyer(Bulletin bulletin) {
		StringBuilder sb = new StringBuilder();
		sb	.append(bulletin.getBuyer().getCnname())
			.append("，您好:")
			.append("您发布的【")
			.append(bulletin.getProjectName())
			.append("】已经选取完成，候选中介如下：")
			.append(bulletin.getBestTradeSupplierNames()) 
			.append(".");
		List<Trade> bestTrades = bulletin.getBestTrades();
		String result = "";
		ShortMessage message = null;
		params = new JSONObject();
		params.put("sb", getParam(bulletin.getBuyer().getCnname()));
		params.put("projectName", getParam(bulletin.getProjectName()));
		if(bestTrades.size() == 1) {
			params.put("bestTradeSupplierCnname", getParam(bestTrades.get(0).getSupplier().getCnname()));
			result = SmsSender.sendSms( getDestNumber(bulletin.getBuyer()),SmsTemplateMapUtils.BEST_CHOOSE_RESULT_NOTIFICATION_TO_OWNER_TEMPLATE,params.toString());
			message = new ShortMessage(sb.toString(),getDestNumber(bulletin.getBuyer()), SmsTemplateMapUtils.BEST_CHOOSE_RESULT_NOTIFICATION_TO_OWNER_TEMPLATE,params.toString());
		}else if (bestTrades.size() == 2){
			params.put("bestTradeSupplierCnname1", getParam(bestTrades.get(0).getSupplier().getCnname()));
			params.put("bestTradeSupplierCnname2", getParam(bestTrades.get(1).getSupplier().getCnname()));
			result = SmsSender.sendSms( getDestNumber(bulletin.getBuyer()),SmsTemplateMapUtils.BEST_CHOOSE_RESULT_NOTIFICATION_TO_OWNER_TWO_TEMPLATE,params.toString());
			message = new ShortMessage(sb.toString(),getDestNumber(bulletin.getBuyer()), SmsTemplateMapUtils.BEST_CHOOSE_RESULT_NOTIFICATION_TO_OWNER_TWO_TEMPLATE,params.toString());
		}else {
			params.put("bestTradeSupplierCnname1", getParam(bestTrades.get(0).getSupplier().getCnname()));
			params.put("bestTradeSupplierCnname2", getParam(bestTrades.get(1).getSupplier().getCnname()));
			params.put("bestTradeSupplierCnname3", getParam(bestTrades.get(2).getSupplier().getCnname()));
			result = SmsSender.sendSms( getDestNumber(bulletin.getBuyer()),SmsTemplateMapUtils.BEST_CHOOSE_RESULT_NOTIFICATION_TO_OWNER_THREE_TEMPLATE,params.toString());
			message = new ShortMessage(sb.toString(),getDestNumber(bulletin.getBuyer()), SmsTemplateMapUtils.BEST_CHOOSE_RESULT_NOTIFICATION_TO_OWNER_THREE_TEMPLATE,params.toString());
		}
		
		saveFeedbackMsg(result, message);
		
		StringBuilder title = new StringBuilder();
		title.append("【")
		.append(bulletin.getProjectName())
		.append("】完成选取通知");
		//消息通知
		notificationService.sendNotification(title.toString(), null, sb.toString(), bulletin.getBuyer());
	}
	
	/**
	 * 向采购方发送结果
	 * 您在东营市网上中介超市发布的【项目名称】公告，已经选取完成，中选人【中介公司名称】。
	 * 
	 * ${sb}，您好：您在东营市网上中介超市发布的${projectName}公告，已经选取完成，中选人${successSupplierName}。
	 */
	public void addOverMessageToBuyer(Bulletin bulletin) {
		StringBuilder sb = new StringBuilder();
		sb	.append((bulletin.getBuyer().getCnname()))
			.append("，您好:")
			.append("您发布的【")
			.append(bulletin.getProjectName())
			.append("】公告，已经选取完成，中选人【")
			.append(bulletin.getSuccessTrade().getSupplier().getCnname())
			.append("】。");
		
		params = new JSONObject();
		params.put("sb", getParam(bulletin.getBuyer().getCnname()));
		params.put("projectName", getParam(bulletin.getProjectName()));
		params.put("successSupplierName", getParam(bulletin.getSuccessTrade().getSupplier().getCnname()));
		String result = SmsSender.sendSms( getDestNumber(bulletin.getBuyer()),SmsTemplateMapUtils.RESULT_NOTIFICATION_TO_OWNER_TEMPLATE,params.toString());
		ShortMessage message = new ShortMessage(sb.toString(),getDestNumber(bulletin.getBuyer()), SmsTemplateMapUtils.RESULT_NOTIFICATION_TO_OWNER_TEMPLATE,params.toString());
		saveFeedbackMsg(result, message);
		StringBuilder title = new StringBuilder();
		title.append("【")
		.append(bulletin.getProjectName())
		.append("】完成选取通知");
		//消息通知
		notificationService.sendNotification(title.toString(), null, sb.toString(), bulletin.getBuyer());
	}
	
	/**
	 * 发送流拍通知
	 * 您在东营市网上中介超市发布的【项目名称】公告，因【无人报名】现已流拍。
	 * 
	 * ${sb}，您好：您在东营市网上中介超市发布的${projectName}公告，因无人报名现已流拍。
	 * 
	 */
	public void addPassMessageToBuyer(Bulletin bulletin) {
		StringBuilder sb = new StringBuilder();
		sb	.append((bulletin.getBuyer().getCnname()))
			.append("，您好:")
			.append("您发布的【")
			.append(bulletin.getProjectName())
			.append("】公告，因【无人报名】现已流拍。");
		
		params = new JSONObject();
		params.put("sb", getParam(bulletin.getBuyer().getCnname()));
		params.put("projectName", getParam(bulletin.getProjectName()));
		String result = SmsSender.sendSms( getDestNumber(bulletin.getBuyer()),SmsTemplateMapUtils.PASS_NOTICE_TEMPLATE,params.toString());
		ShortMessage message = new ShortMessage(sb.toString(),getDestNumber(bulletin.getBuyer()), SmsTemplateMapUtils.PASS_NOTICE_TEMPLATE,params.toString());
		saveFeedbackMsg(result, message);
		StringBuilder title = new StringBuilder();
		title.append("【")
		.append(bulletin.getProjectName())
		.append("】流拍通知");
		//消息通知
		notificationService.sendNotification(title.toString(), null, sb.toString(), bulletin.getBuyer());
	}
	
	/**
	 * 发送流拍通知
	 * 您在东营市网上中介超市发布的【项目名称】公告，因【审核时间已超过报名截止时间】现已流拍。
	 * ${sb}，您好：您在东营市网上中介超市发布的${projectName}公告，因审核时间已超过报名截止时间现已流拍。
	 */
	public void addLatePassMessageToBuyer(Bulletin bulletin) {
		StringBuilder sb = new StringBuilder();
		sb	.append(bulletin.getBuyer().getCnname())
			.append("，您好:")
			.append("您发布的【")
			.append(bulletin.getProjectName())
			.append("】公告，因【无人报名】现已流拍。");
		
		params = new JSONObject();
		params.put("sb", getParam(bulletin.getBuyer().getCnname()));
		params.put("projectName", getParam(bulletin.getProjectName()));
		String result = SmsSender.sendSms( getDestNumber(bulletin.getBuyer()),SmsTemplateMapUtils.AUDIT_OVERDUE_TEMPLATE,params.toString());
		ShortMessage message = new ShortMessage(sb.toString(),getDestNumber(bulletin.getBuyer()), SmsTemplateMapUtils.AUDIT_OVERDUE_TEMPLATE,params.toString());
		saveFeedbackMsg(result, message);
		StringBuilder title = new StringBuilder();
		title.append("【")
		.append(bulletin.getProjectName())
		.append("】流拍通知");
		//消息通知
		notificationService.sendNotification(title.toString(), null, sb.toString(), bulletin.getBuyer());
	}
	
	@Inject
	BulletinService bulletinService;
	/**
	 * 向中介发送提醒
	 * 东营市网上中介超市提醒您参与【项目名称】网上公开选取活动。截至报名时间：【yyyy-MM-dd HH:mm:ss】。
	 * ${sb}，您好：${projectName}网上公开选取活动将于${endingApplyTime}截止报名。
	 */
	public void addInviteMessageToSupplier(Bulletin bulletin) {
		List<Trade> inviteTrades = bulletinService.getInviteTradesByBulletinId(bulletin.getId());
		for (Trade trade : inviteTrades) {			
			StringBuilder content = new StringBuilder();
			content	.append(trade.getSupplier().getCnname())
					.append("，您好:【")
					.append(bulletin.getProjectName())
					.append("】网上公开选取活动将于")
					.append(df.format(bulletin.getEndingApplyTime()))
					.append("截止报名。");
			params = new JSONObject();
			params.put("sb", getParam(trade.getSupplier().getCnname()));
			params.put("projectName", getParam(bulletin.getProjectName()));
			params.put("endingApplyTime", df.format(bulletin.getEndingApplyTime()));
			String result = SmsSender.sendSms( getDestNumber(trade.getSupplier()),SmsTemplateMapUtils.APPLY_NOTICE_TEMPLATE,params.toString());
			ShortMessage message = new ShortMessage(content.toString(),getDestNumber(trade.getSupplier()), SmsTemplateMapUtils.APPLY_NOTICE_TEMPLATE,params.toString());
			saveFeedbackMsg(result, message);
			StringBuilder title = new StringBuilder();
			title.append("【")
			.append(bulletin.getProjectName())
			.append("】邀请通知");
			//消息通知
			notificationService.sendNotification(title.toString(), null, content.toString(), trade.getSupplier());
			
		}
	}
	
	/**
	 * 中介报名成功短信提醒
	 * 
	 * ${sb}，您好：您已成功报名参与${projectName}网上公开选取活动。选取时间：${chooseTime}。
	 * 
	 */
	public void addSuccessAppliedMessageToSupplier(Trade trade) {		
			StringBuilder content = new StringBuilder();
			content	.append(trade.getSupplier().getCnname())
					.append(",您已成功报名参与【")
					.append(trade.getBulletin().getProjectName())
					.append("】网上公开选取活动。选取时间：")
					.append(df.format(trade.getBulletin().getChooseTime()));
			params = new JSONObject();
			params.put("sb", getParam(trade.getSupplier().getCnname()));
			params.put("projectName", getParam(trade.getBulletin().getProjectName()));
			params.put("chooseTime", df.format(trade.getBulletin().getChooseTime()));
			Bulletin bulletin = trade.getBulletin();
			String result = "";
			ShortMessage message = null;
			if(bulletin.getWayOfChoose().equals(ChooseType.Average) || bulletin.getWayOfChoose().equals(ChooseType.Price)){
				result = SmsSender.sendSms( getDestNumber(trade.getSupplier()),SmsTemplateMapUtils.APPLY_SUCCESS_FOR_PRICE_TEMPLATE,params.toString());
				message = new ShortMessage(content.toString(),getDestNumber(trade.getSupplier()), SmsTemplateMapUtils.APPLY_SUCCESS_FOR_PRICE_TEMPLATE,params.toString());
				content.append(",请于选取时间截止前登录系统按照操作提示进行报价。");
			}else{
				result = SmsSender.sendSms( getDestNumber(trade.getSupplier()),SmsTemplateMapUtils.APPLY_SUCCESS_TEMPLATE,params.toString());
				message = new ShortMessage(content.toString(),getDestNumber(trade.getSupplier()), SmsTemplateMapUtils.APPLY_SUCCESS_TEMPLATE,params.toString());
				content.append("。");
			}

			saveFeedbackMsg(result, message);
			StringBuilder title = new StringBuilder();
			title.append("【")
			.append(trade.getBulletin().getProjectName())
			.append("】报名成功通知");
			//消息通知
			notificationService.sendNotification(title.toString(), null, content.toString(), trade.getSupplier());
	}
	
	/**
	 * 用户注册失败时，向申请发送提醒信息
	 * 很抱歉，您在东营市网上中介超市的注册被驳回，请登录官方网站查看原因。
	 * 
	 * ${sb}，您好：很抱歉，您在东营市网上中介超市的注册被驳回，请登录官方网站查看原因。
	 */
	public void addRegisterFailedMessage(User user) {
		if (!(user instanceof ServiceBuyer) && !(user instanceof ServiceSupplier))
			return ;
//		ShortMessage shortMessage = null;
		StringBuilder sb = new StringBuilder();
		sb	.append((user.getCnname()))
			.append("，您好:")
			.append("很抱歉，您在东营市网上中介超市的注册被驳回，请登录官方网站查看原因。");
		String destNumber = getDestNumber(user);
		
		params = new JSONObject();
		params.put("sb", getParam(user.getCnname()));
		String result = SmsSender.sendSms( destNumber,SmsTemplateMapUtils.REGISTER_FAILED_TEMPLATE,params.toString());
		ShortMessage message = new ShortMessage(sb.toString(),destNumber, SmsTemplateMapUtils.REGISTER_FAILED_TEMPLATE,params.toString());
		saveFeedbackMsg(result, message);
		StringBuilder title = new StringBuilder();
		title.append("注册失败通知");
		//消息通知
		notificationService.sendNotification(title.toString(), null, sb.toString(), user);
	}
	
	public void bulletinRechooseNotification(Date oldChooseTime,Bulletin bulletin,ServiceSupplier user) {
		StringBuilder sb = new StringBuilder();
		sb	.append((user.getCnname()))
			.append("，您好:")
			.append(df.format(oldChooseTime))
			.append("的")
			.append(bulletin.getProjectName())
			.append("选取结果因")
			.append(bulletin.getReChooseReason())
			.append("原因作废，现定于")
			.append(df.format(bulletin.getChooseTime()))
			.append("重新进行选取。");
		String destNumber = getDestNumber(user);
		
		params = new JSONObject();
		params.put("supplierName", getParam(user.getCnname()));
		params.put("oldChooseTime", df.format(oldChooseTime));
		params.put("projectName", getParam(bulletin.getProjectName()));
		params.put("reason", getParam(bulletin.getReChooseReason()));
		params.put("newChooseTime", df.format(bulletin.getChooseTime()));
		String result = SmsSender.sendSms( destNumber,SmsTemplateMapUtils.BULLETIN_RECHOOSE_NOTIFICATION_TEMPLATE,params.toString());
		ShortMessage message = new ShortMessage(sb.toString(),destNumber, SmsTemplateMapUtils.BULLETIN_RECHOOSE_NOTIFICATION_TEMPLATE,params.toString());
		saveFeedbackMsg(result, message);
		StringBuilder title = new StringBuilder();
		title.append("【")
		.append(bulletin.getProjectName())
		.append("】结果作废通知");
		//消息通知
		notificationService.sendNotification(title.toString(), null, sb.toString(), user);
	}
	
	/**
	 * @param bulletin
	 * @param user
	 */
	public void bulletinZuoFeiNotification(Bulletin bulletin,ServiceSupplier user) {
		StringBuilder sb = new StringBuilder();
		sb.append("【")	
		.append(bulletin.getProjectName())
			.append("】项目因")
			.append(bulletin.getReChooseReason())
			.append("原因中选结果作废。详情请查看公告内容");
		String destNumber = getDestNumber(user);
		params = new JSONObject();
		params.put("projectName", getParam(bulletin.getProjectName()));
		params.put("reason", getParam(bulletin.getReChooseReason()));
		String result = SmsSender.sendSms( destNumber,SmsTemplateMapUtils.ZUO_FEI_TO_SUCCESS_SUPPLIER_NOTIFICATION_TEMPLATE,params.toString());
		ShortMessage message = new ShortMessage(sb.toString(),destNumber, SmsTemplateMapUtils.ZUO_FEI_TO_SUCCESS_SUPPLIER_NOTIFICATION_TEMPLATE,params.toString());
		saveFeedbackMsg(result, message);
		StringBuilder title = new StringBuilder();
		title.append("【")
		.append(bulletin.getProjectName())
		.append("】结果作废通知");
		//消息通知
		notificationService.sendNotification(title.toString(), null, sb.toString(), user);
		
	}
	
	/**择优顺延 通知中选中介
	 * @param bulletin
	 * @param user
	 */
	public void bestBulletinSYToSupplierNotification(Bulletin bulletin,ServiceSupplier user) {
		StringBuilder sb = new StringBuilder();
		sb.append("【")	
		.append(bulletin.getProjectName())
			.append("】项目因")
			.append(bulletin.getReChooseReason())
			.append("原因中选结果作废，按照分值顺延原则贵公司中选。详情请查看公告内容。");
		String destNumber = getDestNumber(user);
		params = new JSONObject();
		params.put("projectName", getParam(bulletin.getProjectName()));
		params.put("reason", getParam(bulletin.getReChooseReason()));
		String result = SmsSender.sendSms( destNumber,SmsTemplateMapUtils.BEST_SHUN_YAN_TO_SUCCESS_SUPPLIER_NOTIFICATION_TEMPLATE,params.toString());
		ShortMessage message = new ShortMessage(sb.toString(),destNumber, SmsTemplateMapUtils.BEST_SHUN_YAN_TO_SUCCESS_SUPPLIER_NOTIFICATION_TEMPLATE,params.toString());
		saveFeedbackMsg(result, message);
		StringBuilder title = new StringBuilder();
		title.append("【")
		.append(bulletin.getProjectName())
		.append("】顺延通知");
		//消息通知
		notificationService.sendNotification(title.toString(), null, sb.toString(), user);
	}
	
	
	/**择优顺延 通知中选采购方
	 * @param bulletin
	 * @param user
	 */
	public void bestBulletinSYToBuyerNotification(Bulletin bulletin,ServiceSupplier user) {
		StringBuilder sb = new StringBuilder();
		sb.append("【")	
		.append(bulletin.getProjectName())
			.append("】项目因")
			.append(bulletin.getReChooseReason())
			.append("原因中选结果作废,按照分值顺延原则重新选取,中选机构为")
			.append(user.getCnname())
			.append("公司。详情请查看公告内容。");
		String destNumber = getDestNumber(bulletin.getBuyer());
		params = new JSONObject();
		params.put("projectName", getParam(bulletin.getProjectName()));
		params.put("reason", getParam(bulletin.getReChooseReason()));
		params.put("supplierName", user.getCnname());
		String result = SmsSender.sendSms( destNumber,SmsTemplateMapUtils.BEST_SHUN_YAN_TO_BUYER_NOTIFICATION_TEMPLATE,params.toString());
		ShortMessage message = new ShortMessage(sb.toString(),destNumber, SmsTemplateMapUtils.BEST_SHUN_YAN_TO_BUYER_NOTIFICATION_TEMPLATE,params.toString());
		saveFeedbackMsg(result, message);
		StringBuilder title = new StringBuilder();
		title.append("【")
		.append(bulletin.getProjectName())
		.append("】顺延通知");
		//消息通知
		notificationService.sendNotification(title.toString(), null, sb.toString(), user);
	}
	
	/**均价、竞价顺延 通知中选中介
	 * @param bulletin
	 * @param user
	 */
	public void priceBulletinSYToSupplierNotification(Bulletin bulletin,ServiceSupplier user) {
		StringBuilder sb = new StringBuilder();
		sb.append("【")	
		.append(bulletin.getProjectName())
			.append("】项目因")
			.append(bulletin.getReChooseReason())
			.append("原因中选结果作废，按照报价情况顺延原则贵公司中选。详情请查看公告内容。");
		String destNumber = getDestNumber(user);
		params = new JSONObject();
		params.put("projectName", getParam(bulletin.getProjectName()));
		params.put("reason", getParam(bulletin.getReChooseReason()));
		String result = SmsSender.sendSms( destNumber,SmsTemplateMapUtils.PRICE_SHUN_YAN_TO_SUCCESS_SUPPLIER_NOTIFICATION_TEMPLATE,params.toString());
		ShortMessage message = new ShortMessage(sb.toString(),destNumber, SmsTemplateMapUtils.PRICE_SHUN_YAN_TO_SUCCESS_SUPPLIER_NOTIFICATION_TEMPLATE,params.toString());
		saveFeedbackMsg(result, message);
		StringBuilder title = new StringBuilder();
		title.append("【")
		.append(bulletin.getProjectName())
		.append("】顺延通知");
		//消息通知
		notificationService.sendNotification(title.toString(), null, sb.toString(), user);
	}
	
	
	/**均价、报价顺延 通知中选采购方
	 * @param bulletin
	 * @param user
	 */
	public void priceBulletinSYToBuyerNotification(Bulletin bulletin,ServiceSupplier user) {
		StringBuilder sb = new StringBuilder();
		sb.append("【")	
		.append(bulletin.getProjectName())
			.append("】项目因")
			.append(bulletin.getReChooseReason())
			.append("原因中选结果作废,按照报价情况顺延原则重新选取,中选机构为")
			.append(user.getCnname())
			.append("公司。详情请查看公告内容。");
		String destNumber = getDestNumber(bulletin.getBuyer());
		params = new JSONObject();
		params.put("projectName", getParam(bulletin.getProjectName()));
		params.put("reason", getParam(bulletin.getReChooseReason()));
		params.put("supplierName", user.getCnname());
		String result = SmsSender.sendSms( destNumber,SmsTemplateMapUtils.PRICE_SHUN_YAN_TO_BUYER_NOTIFICATION_TEMPLATE,params.toString());
		ShortMessage message = new ShortMessage(sb.toString(),destNumber, SmsTemplateMapUtils.PRICE_SHUN_YAN_TO_BUYER_NOTIFICATION_TEMPLATE,params.toString());
		saveFeedbackMsg(result, message);
		StringBuilder title = new StringBuilder();
		title.append("【")
		.append(bulletin.getProjectName())
		.append("】顺延通知");
		//消息通知
		notificationService.sendNotification(title.toString(), null, sb.toString(), user);
	}
	
	
	
	@Inject
	@SendEmailEvent
	Event<ShortMessage> sendEmailEvent;
	public void sendFailedNotification(String content) {
		String destNumber = "13371528015";
//		String result = SmsSender.sendSms( destNumber,SmsTemplateMapUtils.FAILED_NOTIFICATION_TEMPLATE,params.toString());
		ShortMessage message = new ShortMessage(content,destNumber, SmsTemplateMapUtils.FAILED_NOTIFICATION_TEMPLATE,params.toString());
//		saveFeedbackMsg(result, message);
		sendEmailEvent.fire(message);
		
	}
	
	
	private static String getDestNumber(User user) {
		if (!(user instanceof ServiceBuyer) && !(user instanceof ServiceSupplier))
			return null;
		if (user instanceof ServiceBuyer) {
			ServiceBuyer buyer = (ServiceBuyer) user;
			String fcpn = buyer.getFirstContactorPhoneNumber();
			String destNumber = fcpn;
			String scpn = buyer.getSecondContactorPhoneNumber();
			if (!StringUtils.isBlank(scpn)) {
				destNumber = fcpn.concat(",").concat(scpn);
			}
			return destNumber;
		}
		if (user instanceof ServiceSupplier) {
			ServiceSupplier supplier = (ServiceSupplier) user;
			String fcpn = supplier.getFirstContactorPhoneNumber();
			String destNumber = fcpn;
			String scpn = supplier.getSecondContactorPhoneNumber();
			if (!StringUtils.isBlank(scpn)) {
				destNumber = fcpn.concat(",").concat(scpn);
			}
			return destNumber;
		}
		return null;
	}
	@Inject
	EntityManager entityManager;
//	private   void saveFeedbackMsg(String result,ShortMessage shortMessage) {
//		if(result.equals("")) {
//			shortMessage.setFeedbackMsg("短信接口未打开！");
//		}else if("error".equals(result)) {
//			shortMessage.setFeedbackMsg("请求出现错误，请查看日志！");
//		}else {
//			Map feedBackMap = XmlUtil.loadMapFromString(result);
//			if(!"0".equals(feedBackMap.get("resultcode"))) {
//				shortMessage.setFeedbackMsg(feedBackMap.get("resultcode")+":"+feedBackMap.get("errordescription"));
//			}else {
//				shortMessage.setSendFlag(1);//发送成功
//			}
//		}
//		entityManager.persist(shortMessage);
//		entityManager.flush();
//	}
	
	private  void saveFeedbackMsg(String result,ShortMessage shortMessage) {
		System.out.println(result);
		if(result.equals("")) {
			shortMessage.setFeedbackMsg("短信接口未打开！");
		}else if("error".equals(result)) {
			shortMessage.setFeedbackMsg("请求出现错误，请查看日志！");
		}else {
			JSONObject feedBackMsg = JSONObject.parseObject(result);
			if(!"OK".equals(feedBackMsg.get("Code"))) {
				shortMessage.setFeedbackMsg(feedBackMsg.get("Code")+":"                                                                              +feedBackMsg.get("Message"));
//				sendFailedNotification(shortMessage.getContent());
			}else {
				shortMessage.setSendFlag(1);//发送成功
			}
		}
		entityManager.persist(shortMessage);
		entityManager.flush();
	}
	
	private static final String NOT_SEND_SMS = "SELECT shortMessage " 
			+	" FROM ShortMessage shortMessage"
			+ 	" WHERE shortMessage.sendFlag = 0 ";
	
	public void sendFailedSms() {
		String isDebug = System.getenv("hhsjz_debug");
		if (!isDebug.equals("true")) {
//			Session session = entityManager.unwrap( Session.class );		
//			ScrollableResults sr = session
//		        .createQuery( NOT_SEND_SMS )
//		        .setCacheMode( CacheMode.IGNORE )
//		        .scroll( ScrollMode.FORWARD_ONLY );	
//			
//			int count = 0;
//			while (sr.next()) {
//				count++;
//				ShortMessage shortMessage = (ShortMessage) sr.get(0);
//				String templateCode = shortMessage.getTemplateCode();
//				String params = shortMessage.getParams();
//				String result = SmsSender.sendSms(shortMessage.getDestNumber(),templateCode,params);
//				if(result.equals("")) {
//					shortMessage.setFeedbackMsg("短信接口未打开！");
//				}else if("error".equals(result)) {
//					shortMessage.setFeedbackMsg("请求出现错误，请查看日志！");
//				}else {
//					JSONObject feedBackMsg = JSONObject.parseObject(result);
//					if(!"OK".equals(feedBackMsg.get("Code"))) {
//						shortMessage.setFeedbackMsg(feedBackMsg.get("Code")+":"+feedBackMsg.get("Message"));
//					}else {
//						shortMessage.setSendFlag(1);//发送成功
//					}
//				}
//				session.update(shortMessage);
//				if (count % 100 == 0) {
//					session.flush();
//				}			
//			}
//			session.flush();
		}
	}
	
//	public void sendTestSms() {
//		String isDebug = System.getenv("hhsjz_debug");
//		if(isDebug == null || !isDebug.equals("true")) {
//			ShortMessage shortMessage = new ShortMessage();
//			shortMessage.setDestNumber("17660418726");
//			shortMessage.setContent("短信接口测试！");
//			String result = SmsSender.sendSms(shortMessage.getDestNumber(),shortMessage.getContent());
//			if(result.equals("")) {
//				shortMessage.setFeedbackMsg("短信接口未打开！");
//			}else {
//				Map feedBackMap = XmlUtil.loadMapFromString(result);
//				if(!"0".equals(feedBackMap.get("resultcode"))) {
//					shortMessage.setFeedbackMsg(feedBackMap.get("resultcode")+":"+feedBackMap.get("errordescription"));
//				}else {
//					shortMessage.setSendFlag(1);//发送成功
//				}
//			}
//			entityManager.persist(shortMessage);
//		}
//		
//	}
	
	public static String getParam(String source) {
		if(source == null) return "";
		if (source.length() > 20) {
			 return source.substring(0,17).concat("...");
			} else {
			 return source;
			}
	}
	
	/**
	 * 
	 * 
	 */
	public void sendSmsToSupplier(Trade trade,String smsContent) {
		params = new JSONObject();
		params.put("anything", smsContent);
		String result = SmsSender.sendSms( getDestNumber(trade.getSupplier()),SmsTemplateMapUtils.SELF_DEFINED_TEMPLATE,params.toString());
		ShortMessage message = new ShortMessage(getDestNumber(trade.getSupplier()), SmsTemplateMapUtils.SELF_DEFINED_TEMPLATE,params.toString());
		saveFeedbackMsg(result, message);
	}

	
	public static void main(String[] args) {
//		ServiceBuyer buyer = new ServiceBuyer();
//		buyer.setCnname("wangchangqing");
//		buyer.setFirstContactorPhoneNumber("17660418726");
//		SmsService service = new SmsService();
//		service.addRegisterFailedMessage(buyer);
		System.out.println(getParam("山东鼎元芳华工程项目管理有限公司东营分公司"));
		
	}
	
	
}
